package com.hsgene.image.controller;

import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.image.dto.QiNiuImagesInfoDto;
import com.hsgene.order.exception.OrderErrorCode;
import com.qiniu.util.Auth;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 七牛上传凭证
 *
 * @author wxf
 * @date 2018/8/17 10:40
 **/
@RestController
@RequestMapping("/v1.0/genetic/testing/qiniu/")
public class UploadTokenController {

    /**
     * LOG
     */
    private static Logger LOGGER = LogManager.getLogger(UploadTokenController.class);
    /**
     * 访问秘钥
     */
    @Value("${qiniu.accessKey}")
    private String accessKey;
    /**
     * 加密秘钥
     */
    @Value("${qiniu.secretKey}")
    private String secretKey;

    /**
     * 访问bucket
     */
    @Value("${qiniu.bucketName}")
    private String bucketName;

    /**
     * 获取七牛服务器Token
     *
     * @param oldFileName 需要替换的文件名
     * @return
     */
    @GetMapping("token")
    public ApiResult<String> getUploasToken(String oldFileName) {

        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String token = StringUtils.isEmpty(oldFileName) ? auth.uploadToken(bucketName, oldFileName)
                    : auth.uploadToken(bucketName);
            LOGGER.info("qiniu token is :" + token);
            return ApiResult.succ(token);
        } catch (Exception e) {
            LOGGER.error("获取图片上传token错误，exception = {}", e);
            return new ApiResult<>(-1, "Error_Image_Token_Failed", "获取七牛Token异常", null);
        }
    }

    /**
     * 获取下载凭证
     *
     * @param infoDto 图片地址
     * @return
     */
    @PostMapping("certificate")
    public ApiResult<List<String>> getDownloadCertificate(@RequestBody QiNiuImagesInfoDto infoDto) {
        try {
            if (infoDto == null || infoDto.getImageUrls() == null || infoDto.getImageUrls().isEmpty()) {
                LOGGER.warn("qiniu imageUrls is not null");
                return new ApiResult<>(-1, "failed", "图片地址不能为空", null);
            }
            List<String> result = QiniuCertificateUtil.getDownloadCertificateList(infoDto.getImageUrls());
            LOGGER.info("qiniu certificate is :" + result);
            return new ApiResult<>(200, "success", "获取下载凭证成功", result);
        } catch (Exception e) {
            LOGGER.error("获取下载凭证异常", e);
            return new ApiResult<>(-1, "failed", "获取下载凭证异常", null);
        }
    }
}
